package com.wecan.base.utils;

import com.alibaba.fastjson.JSONObject;
import com.wecan.base.model.RequestInfo;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author liuzhihao
 * @Date 2022.02.22
 * @Version ${version}
 * @Description ${description}
 */
public class HttpUtils {

    public static CloseableHttpClient createHttpClient() {
        CloseableHttpClient build = HttpClientBuilder.create().build();
        return build;
    }

    /**
     * 发起get请求
     *
     * @param requestInfo
     * @return
     */
    public static String doGet(RequestInfo requestInfo) {
        CloseableHttpClient httpClient = createHttpClient();
        Map<String, Object> paramsMap = requestInfo.getParams();
        String params = "";
        if (paramsMap != null) {
            try {
                StringBuilder stringBuilder = new StringBuilder();
                Iterator<String> iterator = paramsMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    Object value = paramsMap.get(key);
                    if (value != null) {
                        stringBuilder.append(key + "=").append(URLEncoder.encode(value.toString(), "utf-8")).append("&");
                    }
                }
                params = stringBuilder.substring(0, stringBuilder.length() - 1);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }
        HttpGet httpGet = new HttpGet(requestInfo.getUrl() + "?" + params);
        CloseableHttpResponse response = null;
        try {
            RequestConfig build = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).setRedirectsEnabled(true).build();
            httpGet.setConfig(build);
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String s = EntityUtils.toString(entity);
                return s;
            }
            return null;
        } catch (ParseException | IOException e) {
            return null;
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发起post请求
     *
     * @param requestInfo
     * @return
     */
    public static String doPost(RequestInfo requestInfo) {
        CloseableHttpClient httpClient = createHttpClient();
        Map<String, Object> paramsMap = requestInfo.getParams();
        String params = "";
        if (paramsMap != null) {
            try {
                StringBuilder stringBuilder = new StringBuilder();
                Iterator<String> iterator = paramsMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    Object value = paramsMap.get(key);
                    if (value != null) {
                        stringBuilder.append(key + "=").append(URLEncoder.encode(value.toString(), "utf-8")).append("&");
                    }
                }
                params = stringBuilder.substring(0, stringBuilder.length() - 1);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }
        HttpPost httpPost = new HttpPost(requestInfo.getUrl() + "?" + params);
        httpPost.setHeader("Content-Type", requestInfo.getContentType());
        if (requestInfo.getDatas() != null) {
            JSONObject datas = requestInfo.getDatas();
            String jsonString = datas.toJSONString();
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(entity);
        }
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
            return null;
        } catch (ParseException | IOException e) {
            return null;
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将通知参数转化为字符串
     * @param request
     * @return
     */
    public static String readData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line; (line = br.readLine()) != null; ) {
                if (result.length() > 0) {
                    result.append("\n");
                }
                result.append(line);
            }
            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
